﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using LeadVinaglue.Models;
using LeadVinaglue.Models.ViewPages;

namespace LeadVinaglue.Repository
{
    public class BannerManagementRepository : BaseManagementRepository
    {
        LeadVinaglueEntities entities = new LeadVinaglueEntities();

        public BannerManagementModel GetModel(string pageType, string roleName,  string keywords, string[] group,  string[] option, string[] payment, string[] position, string startDate, string endDate, string sortBy, string sortOrder, int pageSize, int pageIndex, int id)
        {
            // Update status
            if (id > 0)
            {
                Delete(id);
            }

            // Set value
            BannerManagementModel model = new BannerManagementModel();
            int totalRecord = 0;
            model.ListBanner = GetAll(keywords, group, option, payment, position, startDate, endDate, sortBy, sortOrder, pageSize, pageIndex, ref totalRecord);
            PaginateModel paging = new PaginateModel();

            if (totalRecord > 0)
            {
                paging.PageIndex = pageIndex;
                paging.PageSize = pageSize;
                paging.TotalRecords = totalRecord;
                paging.TotalPages = (totalRecord % pageSize == 0) ? (totalRecord / pageSize) : (totalRecord / pageSize + 1);
            }
            else
            {
                paging.PageIndex = 1;
                paging.PageSize = 10;
                paging.TotalRecords = 0;
                paging.TotalPages = 1;
            }
            model.Paging = paging;

            if (id > 0)
            {
                model.BannerInfo = GetSingle(id);
            }

            return model;
        }

        public BannerManagementModel GetModelByUser(int userId, string pageType, string roleName, string keywords, string[] group, string[] option, string[] payment, string[] position, string startDate, string endDate, string sortBy, string sortOrder, int pageSize, int pageIndex, int id)
        {
            // Update status
            if (id > 0)
            {
                Delete(id);
            }

            // Set value
            BannerManagementModel model = new BannerManagementModel();
            int totalRecord = 0;
            model.ListBanner = GetAll(userId, keywords, group, option, payment, position, startDate, endDate, sortBy, sortOrder, pageSize, pageIndex, ref totalRecord);
            PaginateModel paging = new PaginateModel();

            if (totalRecord > 0)
            {
                paging.PageIndex = pageIndex;
                paging.PageSize = pageSize;
                paging.TotalRecords = totalRecord;
                paging.TotalPages = (totalRecord % pageSize == 0) ? (totalRecord / pageSize) : (totalRecord / pageSize + 1);
            }
            else
            {
                paging.PageIndex = 1;
                paging.PageSize = 10;
                paging.TotalRecords = 0;
                paging.TotalPages = 1;
            }
            model.Paging = paging;

            if (id > 0)
            {
                model.BannerInfo = GetSingle(id);
            }

            return model;
        }

        public BannerManagementModel GetModel(string pageType, string roleName, int pageSize, int pageIndex)
        {
            BannerManagementModel model = new BannerManagementModel();
            int totalRecord = 0;

            model.HeaderView = GetHeader();
            model.MenuItem = GetMenuItems(roleName, pageType);
            model.ListBanner = GetAll(string.Empty, pageSize, pageIndex, ref totalRecord);

            PaginateModel paging = new PaginateModel();
            if (totalRecord > 0)
            {
                paging.PageIndex = pageIndex;
                paging.PageSize = pageSize;
                paging.TotalRecords = totalRecord;
                paging.TotalPages = (totalRecord % pageSize == 0) ? (totalRecord / pageSize) : (totalRecord / pageSize + 1);
            }
            else
            {
                paging.PageIndex = 1;
                paging.PageSize = 10;
                paging.TotalRecords = 0;
                paging.TotalPages = 1;
            }
            model.Paging = paging;

            // Add Options
            model.ListRangeTime = GetRange();
            model.ListBannerGroup = new BannerGroupManagementRepository().GetAllItems();
            model.ListBannerOption = new BannerOptionManagementRepository().GetAllItems();
            model.ListBannerPayment = new PaymentManagementRepository().GetAll(true);
            model.ListBannerPosition = new BannerPositionManagementRepository().GetAllItems();

            return model;
        }

        public BannerManagementModel GetModelByUser(int userId, string pageType, string roleName, int pageSize, int pageIndex)
        {
            BannerManagementModel model = new BannerManagementModel();
            int totalRecord = 0;

            model.HeaderView = GetHeader();
            model.MenuItem = GetMenuItems(roleName, pageType);
            model.ListBanner = GetAll(userId, string.Empty, pageSize, pageIndex, ref totalRecord);

            PaginateModel paging = new PaginateModel();
            if (totalRecord > 0)
            {
                paging.PageIndex = pageIndex;
                paging.PageSize = pageSize;
                paging.TotalRecords = totalRecord;
                paging.TotalPages = (totalRecord % pageSize == 0) ? (totalRecord / pageSize) : (totalRecord / pageSize + 1);
            }
            else
            {
                paging.PageIndex = 1;
                paging.PageSize = 10;
                paging.TotalRecords = 0;
                paging.TotalPages = 1;
            }
            model.Paging = paging;

            // Add Options
            model.ListRangeTime = GetRange();
            model.ListBannerGroup = new BannerGroupManagementRepository().GetAllItems();
            model.ListBannerOption = new BannerOptionManagementRepository().GetAllItems();
            model.ListBannerPayment = new PaymentManagementRepository().GetAll(true);
            model.ListBannerPosition = new BannerPositionManagementRepository().GetAllItems();

            return model;
        }

        public BannerManagementModel GetModel(string pageType, string roleName, int id)
        {
            BannerManagementModel model = new BannerManagementModel();

            model.HeaderView = GetHeader();
            model.MenuItem = GetMenuItems(roleName, pageType);
            model.BannerInfo = GetSingle(id);

            model.ListBannerGroup = new BannerGroupManagementRepository().GetAllItems();
            model.ListBannerOption = new BannerOptionManagementRepository().GetAllItems();
            model.ListBannerPayment = new PaymentManagementRepository().GetAll(true);
            model.ListBannerPosition = new BannerPositionManagementRepository().GetAllItems();

            return model;
        }

        public BannerManagementModel GetModelByUser(string pageType, string roleName, int id, int userId)
        {
            BannerManagementModel model = new BannerManagementModel();

            model.HeaderView = GetHeader();
            model.MenuItem = GetMenuItems(roleName, pageType);
            model.BannerInfo = GetSingle(id, userId);

            model.ListBannerGroup = new BannerGroupManagementRepository().GetAllItems();
            model.ListBannerOption = new BannerOptionManagementRepository().GetAllItems();
            model.ListBannerPayment = new PaymentManagementRepository().GetAll(true);
            model.ListBannerPosition = new BannerPositionManagementRepository().GetAllItems();

            return model;
        }

        #region #Private functions
        private List<OptionModel> GetRange()
        {
            List<OptionModel> list = new List<OptionModel>();

            OptionModel model;
            model = new OptionModel { ID = DateTime.Now.ToString("MM/dd/yyyy") + "|" + DateTime.Now.ToString("MM/dd/yyyy"), Name = "Hôm nay" };
            list.Add(model);

            model = new OptionModel { ID = DateTime.Now.AddDays(-1).ToString("MM/dd/yyyy") + "|" + DateTime.Now.AddDays(-1).ToString("MM/dd/yyyy"), Name = "Hôm qua" };
            list.Add(model);

            model = new OptionModel { ID = DateTime.Now.AddDays(-7).ToString("MM/dd/yyyy") + "|" + DateTime.Now.ToString("MM/dd/yyyy"), Name = "7 ngày trước" };
            list.Add(model);

            model = new OptionModel { ID = DateTime.Now.AddDays(-30).ToString("MM/dd/yyyy") + "|" + DateTime.Now.ToString("MM/dd/yyyy"), Name = "30 ngày trước" };
            list.Add(model);

            DateTime startDate = new DateTime();
            DateTime endDate = new DateTime();

            // before this month
            startDate = Utility.LeadTools.GetFirstDayOfMonth(DateTime.Now.AddMonths(-1).Month, DateTime.Now.AddMonths(-1).Year);
            endDate = Utility.LeadTools.GetLastDayOfMonth(startDate);
            model = new OptionModel { ID = startDate.ToString("MM/dd/yyyy") + "|" + endDate.ToString("MM/dd/yyyy"), Name = "Tháng trước" };
            list.Add(model);

            // before 2 month
            startDate = Utility.LeadTools.GetFirstDayOfMonth(DateTime.Now.AddMonths(-2).Month, DateTime.Now.AddMonths(-2).Year);
            endDate = Utility.LeadTools.GetLastDayOfMonth(startDate.AddMonths(1));
            model = new OptionModel { ID = startDate.ToString("MM/dd/yyyy") + "|" + endDate.ToString("MM/dd/yyyy"), Name = "2 tháng trước" };
            list.Add(model);

            // Before 3 month
            startDate = Utility.LeadTools.GetFirstDayOfMonth(DateTime.Now.AddMonths(-3).Month, DateTime.Now.AddMonths(-3).Year);
            endDate = Utility.LeadTools.GetLastDayOfMonth(startDate.AddMonths(2));
            model = new OptionModel { ID = startDate.ToString("MM/dd/yyyy") + "|" + endDate.ToString("MM/dd/yyyy"), Name = "3 tháng trước" };
            list.Add(model);

            // This month
            startDate = Utility.LeadTools.GetFirstDayOfMonth(DateTime.Now.Month, DateTime.Now.Year);
            endDate = Utility.LeadTools.GetLastDayOfMonth(startDate);
            model = new OptionModel { ID = startDate.ToString("MM/dd/yyyy") + "|" + endDate.ToString("MM/dd/yyyy"), Name = "Tháng này" };
            list.Add(model);

            // All time
            model = new OptionModel { ID = "-1", Name = "Tất cả" };
            list.Add(model);

            return list;
        }
        
        private List<BannerModel> GetAll(string keywords, string[] groupId, string[] optionId, string[] paymentId, string[] positionId, string startDate, string endDate, string sortBy, string sortOrder, int pageSize, int pageIndex, ref int total)
        {
            List<BannerModel> list = new List<BannerModel>();
            List<Banner> listTemp = new List<Banner>();
            var banners = (from c in entities.Banners
                           select c);


            List<string> arrGroup = new List<string>();
            List<int> arrOption = new List<int>();
            List<int> arrPayment = new List<int>();
            List<string> arrPosition = new List<string>();

            // Check conditions
            if (!string.IsNullOrEmpty(keywords))
                banners = banners.Where(c => c.Title.Contains(keywords));

            // Group list
            if (groupId.Length > 0 && groupId[0] != "0")
            {
                for (int i = 0; i < groupId.Length; i++)
                {
                    arrGroup.Add(groupId[i]);
                }
                banners = banners.Where(c => arrGroup.Contains(c.GroupID));
            }

            // Option list
            if (optionId.Length > 0 && int.Parse(optionId[0]) > 0)
            {
                for (int i = 0; i < optionId.Length; i++)
                {
                    arrOption.Add(int.Parse(optionId[i]));
                }
                banners = banners.Where(c => arrOption.Contains(c.OptionID.Value));
            }

            // Payment list
            if (paymentId.Length > 0 && int.Parse(paymentId[0]) > 0)
            {
                for (int i = 0; i < paymentId.Length; i++)
                {
                    arrPayment.Add(int.Parse(paymentId[i]));
                }
                banners = banners.Where(c => arrPayment.Contains(c.PaymentID.Value));
            }

            // Position list
            if (positionId.Length > 0 && positionId[0] != "0")
            {
                for (int i = 0; i < positionId.Length; i++)
                {
                    arrPosition.Add(positionId[i]);
                }
                banners = banners.Where(c => arrPosition.Contains(c.PositionID));
            }

            DateTime isStartDate;
            if (!string.IsNullOrEmpty(startDate) && DateTime.TryParse(startDate, out isStartDate))
            {
                DateTime sDate = Convert.ToDateTime(startDate);
                banners = banners.Where(c => c.DateCreated >= sDate);
            }
            DateTime isEndDate;
            if (!string.IsNullOrEmpty(endDate) && DateTime.TryParse(endDate, out isEndDate))
            {
                DateTime eDate = Convert.ToDateTime(endDate);
                banners = banners.Where(c => c.DateCreated <= eDate);
            }
            
            // Get total count
            try
            {
                if (banners != null && banners.Count() > 0)
                {
                    total = banners.Count();

                    // Sort by Column|Order
                    sortOrder = sortOrder.ToUpper();
                    sortBy = sortBy.ToUpper();
                    switch (sortBy)
                    {
                        case "TITLE":
                            {
                                if(sortOrder == "ASC")
                                    listTemp = banners.OrderBy(c => c.Title).ToList().Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
                                else
                                    listTemp = banners.OrderByDescending(c => c.Title).ToList().Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
                                break;
                            }
                        case "SHORTDESC":
                            {
                                if (sortOrder == "ASC")
                                    listTemp = banners.OrderBy(c => c.ShortDesc).ToList().Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
                                else
                                    listTemp = banners.OrderByDescending(c => c.ShortDesc).ToList().Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
                                break;
                            }
                        case "DATECREATED":
                            {
                                if (sortOrder == "ASC")
                                    listTemp = banners.OrderBy(c => c.DateCreated).ToList().Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
                                else
                                    listTemp = banners.OrderByDescending(c => c.DateCreated).ToList().Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
                                break;
                            }
                        case "ACTIVE":
                            {
                                if (sortOrder == "ASC")
                                    listTemp = banners.OrderBy(c => c.Active).ToList().Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
                                else
                                    listTemp = banners.OrderByDescending(c => c.Active).ToList().Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
                                break;
                            }
                        default:
                            {
                                if(sortOrder == "ASC")
                                    listTemp = banners.OrderByDescending(c => c.DateCreated).ToList().Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
                                else
                                    listTemp = banners.OrderByDescending(c => c.DateCreated).ToList().Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
                                break;
                            }
                    }
                }
            }
            catch (Exception ex)
            {
                Helpers.ErrorHandle.AddError(ex.Message);
            }

            // Add list
            foreach (var item in listTemp)
            {
                BannerModel model = new BannerModel();

                model.ID = item.ID;
                model.GroupId = item.GroupID;
                model.PositionId = item.PositionID;
                model.Title = item.Title;
                model.ShortDesc = item.ShortDesc;
                model.LongDesc = item.LongDesc;
                model.ImageUrl = item.ImageURL;
                model.FlashUrl = item.FlashURL;
                model.HTML = item.HTML;
                model.CreationDate = Convert.ToDateTime(item.DateCreated).ToString("dd-MM-yyyy");
                model.Start = Convert.ToDateTime(item.StartDate).ToString("dd-MM-yyyy");
                model.End = Convert.ToDateTime(item.EndDate).ToString("dd-MM-yyyy");
                model.NumOfClick = Convert.ToInt32(item.NumberOfClick);
                model.NumOfDisplay = Convert.ToInt32(item.NumberOfDisplay);
                model.Active = item.Active;

                list.Add(model);
            }

            return list;
        }


        private List<BannerModel> GetAll(int userId, string keywords, string[] groupId, string[] optionId, string[] paymentId, string[] positionId, string startDate, string endDate, string sortBy, string sortOrder, int pageSize, int pageIndex, ref int total)
        {
            List<BannerModel> list = new List<BannerModel>();
            List<Banner> listTemp = new List<Banner>();
            var banners = (from c in entities.Banners
                           where c.CreatedByUserID == userId
                           select c);


            List<string> arrGroup = new List<string>();
            List<int> arrOption = new List<int>();
            List<int> arrPayment = new List<int>();
            List<string> arrPosition = new List<string>();

            // Check conditions
            if (!string.IsNullOrEmpty(keywords))
                banners = banners.Where(c => c.Title.Contains(keywords));

            // Group list
            if (groupId.Length > 0 && groupId[0] != "0")
            {
                for (int i = 0; i < groupId.Length; i++)
                {
                    arrGroup.Add(groupId[i]);
                }
                banners = banners.Where(c => arrGroup.Contains(c.GroupID));
            }

            // Option list
            if (optionId.Length > 0 && int.Parse(optionId[0]) > 0)
            {
                for (int i = 0; i < optionId.Length; i++)
                {
                    arrOption.Add(int.Parse(optionId[i]));
                }
                banners = banners.Where(c => arrOption.Contains(c.OptionID.Value));
            }

            // Payment list
            if (paymentId.Length > 0 && int.Parse(paymentId[0]) > 0)
            {
                for (int i = 0; i < paymentId.Length; i++)
                {
                    arrPayment.Add(int.Parse(paymentId[i]));
                }
                banners = banners.Where(c => arrPayment.Contains(c.PaymentID.Value));
            }

            // Position list
            if (positionId.Length > 0 && positionId[0] != "0")
            {
                for (int i = 0; i < positionId.Length; i++)
                {
                    arrPosition.Add(positionId[i]);
                }
                banners = banners.Where(c => arrPosition.Contains(c.PositionID));
            }

            DateTime isStartDate;
            if (!string.IsNullOrEmpty(startDate) && DateTime.TryParse(startDate, out isStartDate))
            {
                DateTime sDate = Convert.ToDateTime(startDate);
                banners = banners.Where(c => c.DateCreated >= sDate);
            }
            DateTime isEndDate;
            if (!string.IsNullOrEmpty(endDate) && DateTime.TryParse(endDate, out isEndDate))
            {
                DateTime eDate = Convert.ToDateTime(endDate);
                banners = banners.Where(c => c.DateCreated <= eDate);
            }

            // Get total count
            try
            {
                if (banners != null && banners.Count() > 0)
                {
                    total = banners.Count();

                    // Sort by Column|Order
                    sortOrder = sortOrder.ToUpper();
                    sortBy = sortBy.ToUpper();
                    switch (sortBy)
                    {
                        case "TITLE":
                            {
                                if (sortOrder == "ASC")
                                    listTemp = banners.OrderBy(c => c.Title).ToList().Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
                                else
                                    listTemp = banners.OrderByDescending(c => c.Title).ToList().Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
                                break;
                            }
                        case "SHORTDESC":
                            {
                                if (sortOrder == "ASC")
                                    listTemp = banners.OrderBy(c => c.ShortDesc).ToList().Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
                                else
                                    listTemp = banners.OrderByDescending(c => c.ShortDesc).ToList().Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
                                break;
                            }
                        case "DATECREATED":
                            {
                                if (sortOrder == "ASC")
                                    listTemp = banners.OrderBy(c => c.DateCreated).ToList().Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
                                else
                                    listTemp = banners.OrderByDescending(c => c.DateCreated).ToList().Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
                                break;
                            }
                        case "ACTIVE":
                            {
                                if (sortOrder == "ASC")
                                    listTemp = banners.OrderBy(c => c.Active).ToList().Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
                                else
                                    listTemp = banners.OrderByDescending(c => c.Active).ToList().Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
                                break;
                            }
                        default:
                            {
                                if (sortOrder == "ASC")
                                    listTemp = banners.OrderByDescending(c => c.DateCreated).ToList().Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
                                else
                                    listTemp = banners.OrderByDescending(c => c.DateCreated).ToList().Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
                                break;
                            }
                    }
                }
            }
            catch (Exception ex)
            {
                Helpers.ErrorHandle.AddError(ex.Message);
            }

            // Add list
            foreach (var item in listTemp)
            {
                BannerModel model = new BannerModel();

                model.ID = item.ID;
                model.GroupId = item.GroupID;
                model.PositionId = item.PositionID;
                model.Title = item.Title;
                model.ShortDesc = item.ShortDesc;
                model.LongDesc = item.LongDesc;
                model.ImageUrl = item.ImageURL;
                model.FlashUrl = item.FlashURL;
                model.HTML = item.HTML;
                model.CreationDate = Convert.ToDateTime(item.DateCreated).ToString("dd-MM-yyyy");
                model.Start = Convert.ToDateTime(item.StartDate).ToString("dd-MM-yyyy");
                model.End = Convert.ToDateTime(item.EndDate).ToString("dd-MM-yyyy");
                model.NumOfClick = Convert.ToInt32(item.NumberOfClick);
                model.NumOfDisplay = Convert.ToInt32(item.NumberOfDisplay);
                model.Active = item.Active;

                list.Add(model);
            }

            return list;
        }

        private List<BannerModel> GetAll(string keywords, int pageSize, int pageIndex, ref int total)
        {
            List<BannerModel> list = new List<BannerModel>();

            var banners = (from c in entities.Banners
                           select c);

            // Check conditions
            if (!string.IsNullOrEmpty(keywords))
                banners = banners.Where(c => c.Title.Contains(keywords));
            
            // Get total count
            total = banners.Count();

            var items = banners.OrderByDescending(c => c.ID).ToList().Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();

            foreach (var item in items)
            {
                BannerModel model = new BannerModel();

                model.ID = item.ID;
                model.GroupId = item.GroupID;
                model.PositionId = item.PositionID;
                model.Title = item.Title;
                model.ShortDesc = item.ShortDesc;
                model.LongDesc = item.LongDesc;
                model.ImageUrl = item.ImageURL;
                model.FlashUrl = item.FlashURL;
                model.HTML = item.HTML;
                model.CreationDate = Convert.ToDateTime(item.DateCreated).ToString("dd-MM-yyyy");
                model.Start = Convert.ToDateTime(item.StartDate).ToString("dd-MM-yyyy");
                model.End = Convert.ToDateTime(item.EndDate).ToString("dd-MM-yyyy");
                model.NumOfClick = Convert.ToInt32(item.NumberOfClick);
                model.NumOfDisplay = Convert.ToInt32(item.NumberOfDisplay);
                model.Active = item.Active;

                list.Add(model);
            }

            return list;
        }
        
        private List<BannerModel> GetAll(int userId, string keywords, int pageSize, int pageIndex, ref int total)
        {
            List<BannerModel> list = new List<BannerModel>();

            var banners = (from c in entities.Banners
                           where c.CreatedByUserID == userId
                           select c);

            // Check conditions
            if (!string.IsNullOrEmpty(keywords))
                banners = banners.Where(c => c.Title.Contains(keywords));
            
            // Get total count
            total = banners.Count();

            var items = banners.OrderByDescending(c => c.ID).ToList().Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();

            foreach (var item in items)
            {
                BannerModel model = new BannerModel();

                model.ID = item.ID;
                model.GroupId = item.GroupID;
                model.PositionId = item.PositionID;
                model.Title = item.Title;
                model.ShortDesc = item.ShortDesc;
                model.LongDesc = item.LongDesc;
                model.ImageUrl = item.ImageURL;
                model.FlashUrl = item.FlashURL;
                model.HTML = item.HTML;
                model.CreationDate = Convert.ToDateTime(item.DateCreated).ToString("dd-MM-yyyy");
                model.Start = Convert.ToDateTime(item.StartDate).ToString("dd-MM-yyyy");
                model.End = Convert.ToDateTime(item.EndDate).ToString("dd-MM-yyyy");
                model.NumOfClick = Convert.ToInt32(item.NumberOfClick);
                model.NumOfDisplay = Convert.ToInt32(item.NumberOfDisplay);
                model.Active = item.Active;

                list.Add(model);
            }

            return list;
        }

        private bool IsExist(string[] arr, int? id)
        {
            bool isExist=false;

            for(int i=0;i<arr.Length;i++)
            {
                if(int.Parse(arr[i]) == id)
                {
                    isExist=true;
                    break;
                }
            }

            return isExist;
        }
        #endregion

        #region Reference function
        public Banner GetSingle(int id, int userId)
        {
            return (from _object in entities.Banners 
                    where _object.ID == id && _object.CreatedByUserID == userId
                    select _object).FirstOrDefault();
        }

        public Banner GetSingle(int id)
        {
            return (from _object in entities.Banners where _object.ID == id select _object).FirstOrDefault();
        }
        
        public void Create([Bind(Exclude = "ID, DateCreated")] Banner _object)
        {
            _object.DateCreated = System.DateTime.Now;
            entities.AddToBanners(_object);
            entities.SaveChanges();
        }

        public void Delete(int id)
        {
            var _object = (from _list in entities.Banners where _list.ID == id select _list).First();
            entities.DeleteObject(_object);
            entities.SaveChanges();
        }

        public void Update(Banner _object)
        {
            _object.DateCreated = System.DateTime.Now;
            entities.SaveChanges();
        }

        public void Save([Bind(Exclude = "ID")] Banner _object)
        {
            _object.EntityKey = (from Banner ac in entities.Banners where ac.ID == _object.ID select ac).FirstOrDefault().EntityKey;
            _object.DateCreated = System.DateTime.Now;
            entities.SaveChanges();
        }
        #endregion
    }
}
